package cn.task;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;

import cn.pojo.Item;
import cn.service.ItemService;
import cn.util.HttpUtils;

@Component
public class ItemTask {
	
	@Resource
	private HttpUtils httpUtils;
	@Resource
	private ItemService itemService;
	private static final ObjectMapper Mapper = new ObjectMapper();
	//每隔100秒钟就下载一次
	@Scheduled(fixedDelay = 100*1000)
	public void itemTask() throws Exception{
		//声明需要下解析的初始地址
		String url = "https://search.jd.com/Search?keyword=%E6%89%8B%E6%9C%BA&enc=utf-8"
				+ "&qrst=1&rt=1&stop=1&vt=2&wq=%E6%89%8B%E6%9C%BA&s=58&click=0&page=";
		//按照页码对手机的搜索结果进行遍历
		for(int i=1;i<10;i=i+2) {
			String html = httpUtils.doGetHtml(url+i);
			//解析页面，获取商品数据并存储
			this.parse(html);
		}
	}
	private void parse(String html) {
		//解析Html获取dom原型
		Document document = Jsoup.parse(html);
		//获取spu
		Elements spuEles = document.select("div#J_goodsList > ul > li");
		for(Element spuEle:spuEles) {
			Long spu = Long.parseLong(spuEle.attr("data-spu"));
			//获取sku
			Elements skuEles = spuEle.select("li.ps-item");
			for(Element skuEle:skuEles) {
				Long sku = Long.parseLong(skuEle.select("data-sku").attr("data-sku"));
				//根据sku查询商品数据，如果商品存在，则不插入该数据
				Item item = new Item();
				item.setSku(sku);
				List<Item> list = itemService.findAll(item);
				//如果已经存在则直接进入下一个循环
				if(list.size()>0) {
					continue;
				}
				item.setSpu(spu);
				//获取商品详情的url
				String itemUrl = "https://item.jd.com/"+sku+".html";
				item.setUrl(itemUrl);
				//商品图片
				String pic = "https:"+skuEle.select("img[data-sku]").first().attr("data-lazy-img");
				System.out.println("++++++++++++++++++++++++++++++"+pic);
				pic.replace("/n9/", "/n1/");
				//下载图片
				String imageName = httpUtils.doGetImage(pic);
 				item.setPic(imageName);
 				
 				//获取商品价格
 				String priceJson = this.httpUtils.doGetHtml("https://p.3.cn/prices/mgets?skuIds=J_"+sku);
				try {
					item.setPrice(Mapper.readTree(priceJson).get(0).get("p").asDouble());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				//获取商品标题
				String itemInfo = item.getUrl();
				String title = Jsoup.parse(itemInfo).select("div.sku-name").text();
				item.setTitle(title);
				item.setCreated(new Date());
				item.setCreated(item.getCreated());
				
				//保存商品数据到数据库中
				itemService.save(item);
			}
		}
		
	}
}
